import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int deepestLeavesSum(TreeNode root) {
        if (root == null) return 0;

        Queue<TreeNode> q = new LinkedList<>();
        int res = 0, next = 0;

        q.offer(root);
        while (!q.isEmpty()) {
            int n = q.size();
            res = next;
            next = 0;
            for (int i = 0; i < n; i++) {
                TreeNode cur = q.poll();
                if (cur == null) continue;
                next += cur.val;
                q.offer(cur.left);
                q.offer(cur.right);
            }
        }
        return res;
    }
}